package cn.com.eado.crm.v.fragment


import android.text.Editable
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.eado.crm.R
import cn.com.eado.crm.app.KEY_USER_ID
import cn.com.eado.crm.app.MyApp
import cn.com.eado.crm.app.extenstion.toast
import cn.com.eado.crm.app.utils.SpUtil
//import cn.com.eado.crm.m.db.Contact
import cn.com.eado.crm.m.db.MyDatabase
import cn.com.eado.crm.model.LoadStatus
import cn.com.eado.crm.v.adapter.RVCompanyAdapter
import cn.com.eado.crm.vm.CompanyViewModel
import cn.com.eado.preado.app.utils.autoCleared
import kotlinx.android.synthetic.main.fragment_company_search.*
import kotlin.concurrent.thread
import android.net.Uri
import android.content.Intent
import androidx.recyclerview.widget.RecyclerView
import cn.com.eado.crm.databinding.FragmentCompanySearchBinding
import cn.com.eado.crm.m.db.Company
import cn.com.eado.crm.m.db.CusUser
import cn.com.eado.crm.model.RetryCallback


/**
 * A simple [Fragment] subclass.
 */
class CompanySearchFragment : BaseBindingFragment<FragmentCompanySearchBinding>(R.layout.fragment_company_search) {

    private var vm by autoCleared<CompanyViewModel>()
    private var adapter by autoCleared<RVCompanyAdapter>()
    private var mList: MutableList<Company.Row>? = null
    private var total = 0
    private var hasNoMore = false
    private var loadMoreState = 0


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun initTheFragment() {
        initView()
        initViewModel()
        initBinding()
//        loadData()
    }

    private fun initView() {
        initTitleBar()
        initRecyclerView()
    }

    private fun initTitleBar() {
        titleBar8.setHint("企业名称")
        titleBar8.searchCallback = { s ->
            loadData(s)
        }
    }

    private fun initRecyclerView() {
        recyclerView4.setHasFixedSize(true)
        recyclerView4.isNestedScrollingEnabled = false
        recyclerView4.layoutManager = LinearLayoutManager(activity)
        val adapter = RVCompanyAdapter({ view, pos, bean ->  //click
            thread {
//                val contact = MyDatabase.getInstance().contactDao().queryWithName(bean.CompanyName)
//                activity?.runOnUiThread {
//                    if(contact != null) showContact(contact)
//                    else activity?.toast("没有联系人!")
//                }
            }
        })
        recyclerView4.adapter = adapter
        this.adapter = adapter
        //set load more listener
        recyclerView4.addOnScrollListener(object: RecyclerView.OnScrollListener(){  //监听滑动到底部加载下一页
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val lastPosition = layoutManager.findLastVisibleItemPosition()
                if (lastPosition == adapter.itemCount - 1) {
                    if (mList?.size!! >= total && total > 0){
                        if (!hasNoMore) {
                            hasNoMore = true
                            activity?.toast("没有更多了")
                        }
                    }else{
                        if (loadMoreState == 0) {
                            loadMoreState = 1
                            vm.page += 1
                        }
                        if (loadMoreState == 1){
                            binding.loadingMore = true
                            vm.loadNextPage()
                        }
                    }
                }else{
                    hasNoMore = false
                }
            }
        })
    }

    private fun initViewModel(){
        vm = ViewModelProviders.of(this).get(CompanyViewModel::class.java)
        vm.company.observe(this, Observer {
            if (it.status == LoadStatus.SUCCESS){
                if (it.data?.rows?.isNotEmpty() == true){
                    Log.e("tag", "data size=${it.data?.rows?.size}")
                    mList?.addAll(it.data.rows)
                    this.adapter.refresh(mList)
                    //about load more
                    total = it.data.total
                    binding.loadingMore?.let{
                        binding.loadingMore = false
                        if (loadMoreState == 1) vm.page += 1
                    }
                }else{
                    adapter.refresh(mList)
                }
            }else if (it.status == LoadStatus.ERROR){
                //about load more
                binding.loadingMore?.let{
                    binding.loadingMore = false
                }
            }
        })
    }

    private fun initBinding(){
        binding.lifecycleOwner = viewLifecycleOwner
        binding.result = vm.company
        binding.callback = object : RetryCallback {
            override fun retry() {
                vm.refresh()
            }
        }
    }

    private fun loadData(s: String){
        if (mList == null) mList = mutableListOf()
        else mList?.clear()
        vm.companyName = s
        vm.setLoadCompany(true)
    }



    /////////////////////////////////////////contact/////////////////////////////////////////////
    private fun showContact(contact: CusUser){
        Log.e("tag", "........")
        val name = "联系人"
        val layout = initContact(contact)
        AlertDialog.Builder(activity!!)
            .setTitle(name)
            .setView(layout)
//            .setPositiveButton("提交", null)//结合下面的dialog.getButton，保证点击确定不关闭dialog
            .setNegativeButton("关闭"){ dialog, pos -> }
            .show()
    }

    private fun initContact(contact: CusUser): View {
        val layout = View.inflate(activity, R.layout.contact, null)
        val s = "    企业："
        layout.findViewById<TextView>(R.id.tvName).text = s
        val tvDepartment = layout.findViewById<TextView>(R.id.tvDepartment)
        val tvPeople = layout.findViewById<TextView>(R.id.tvPeople)
        val tvPosition = layout.findViewById<TextView>(R.id.tvPosition)
        val tvPart = layout.findViewById<TextView>(R.id.tvPart)
        val tvPhone = layout.findViewById<TextView>(R.id.tvPhone)
        val tvCellPhone = layout.findViewById<TextView>(R.id.tvCellPhone)
        val tvEmail = layout.findViewById<TextView>(R.id.tvEmail)
        val tvRemark = layout.findViewById<TextView>(R.id.tvRemark)
        //
//        tvDepartment.text = Editable.Factory.getInstance().newEditable(contact.name)
//        tvPeople.text = Editable.Factory.getInstance().newEditable(contact.people)
//        tvPosition.text = Editable.Factory.getInstance().newEditable(contact.position)
//        tvPart.text = Editable.Factory.getInstance().newEditable(contact.department)
//        tvPhone.text = Editable.Factory.getInstance().newEditable(contact.tel)
//        tvCellPhone.text = Editable.Factory.getInstance().newEditable(contact.cellPhone)
//        tvEmail.text = Editable.Factory.getInstance().newEditable(contact.email)
//        tvRemark.text = Editable.Factory.getInstance().newEditable(contact.remark)
        //
        tvPhone.setOnClickListener {
            val intent = Intent(Intent.ACTION_DIAL)
            intent.data = Uri.parse("tel:${tvPhone.text.toString()}")
            startActivity(intent)
        }
        tvCellPhone.setOnClickListener {
            val intent = Intent(Intent.ACTION_DIAL)
            intent.data = Uri.parse("tel:${tvCellPhone.text.toString()}")
            startActivity(intent)
        }

        return layout
    }

}
